<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>任务节点管理</span>
        <el-radio-group v-model="orderType" style="float: right;" @change="handleOrderTypeChange">
          <el-radio-button label="published">我发布的订单</el-radio-button>
          <el-radio-button label="accepted">我接受的订单</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 未登录提示 -->
      <el-alert
        v-if="!currentUser || !currentUser.id"
        title="请先登录"
        type="warning"
        :closable="false"
        show-icon>
      </el-alert>

      <!-- 已登录内容 -->
      <div v-else>
        <!-- 订单选择部分 -->
        <div class="order-selection" style="margin-bottom: 20px;">
          <el-select 
            v-model="selectedOrderId" 
            placeholder="请选择订单" 
            style="width: 100%;"
            :loading="loading"
            @change="handleOrderSelect">
            <el-option
              v-for="order in orderList"
              :key="order.id"
              :label="getOrderLabel(order)"
              :value="order.id">
              <span style="float: left">{{ order.petName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ formatDate(order.startTime) }} ~ {{ formatDate(order.endTime) }}
              </span>
            </el-option>
          </el-select>
        </div>

        <!-- 无订单或加载中的提示 -->
        <el-empty 
          v-if="!loading && !selectedOrderId && orderList.length === 0" 
          :description="getEmptyDescription()">
          <template #description>
            <p>{{ getEmptyDescription() }}</p>
            <p v-if="currentUser && currentUser.id" style="color: #909399; font-size: 14px;">
              {{ orderType === 'published' ? '您可以点击下方按钮发布新的订单' : '您可以浏览并接受他人发布的订单' }}
            </p>
          </template>
          <el-button v-if="orderType === 'published'" type="primary" @click="$router.push('/pet-care/publish')">
            发布新订单
          </el-button>
          <el-button v-else type="primary" @click="$router.push('/pet-care/available')">
            查看可接订单
          </el-button>
        </el-empty>

        <!-- 加载中提示 -->
        <div v-if="loading" style="text-align: center; padding: 20px;">
          <el-spinner></el-spinner>
          <p>正在加载订单数据...</p>
        </div>

        <!-- 订单详情部分 -->
        <el-descriptions v-if="selectedOrderId" title="订单信息" :column="2" border>
          <el-descriptions-item label="订单ID">{{ orderId }}</el-descriptions-item>
          <el-descriptions-item label="宠物名称">{{ petName }}</el-descriptions-item>
          <el-descriptions-item label="宠物类型">{{ petType }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="orderStatusType">{{ orderStatusText }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 发布者设置任务节点部分 -->
        <div v-if="orderType === 'published' && !taskNodesCreated && selectedOrderId" style="margin-top: 20px;">
          <el-divider content-position="left">设置任务节点</el-divider>
          <el-form :model="taskNodeForm" ref="taskNodeForm" label-width="100px">
            <el-form-item
              v-for="(node, index) in taskNodes"
              :key="index"
              :label="`任务${index + 1}`"
              :prop="`taskNodes[${index}].title`"
              :rules="{ required: true, message: '任务名称不能为空', trigger: 'blur' }">
              <div class="task-node-item">
                <el-input v-model="node.title" placeholder="任务名称" style="width: 200px; margin-right: 10px;"></el-input>
                <el-input v-model="node.description" placeholder="任务描述" style="width: 300px; margin-right: 10px;"></el-input>
                <el-button
                  @click.prevent="removeTaskNode(index)"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  plain
                  size="mini">
                </el-button>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button @click="addTaskNode" type="primary" plain icon="el-icon-plus">添加任务</el-button>
              <el-button type="success" @click="submitTaskNodes">确认提交</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 任务节点列表和处理部分 -->
        <div v-if="taskNodesCreated && selectedOrderId">
          <el-divider content-position="left">任务列表</el-divider>
          <el-table :data="taskNodes" style="width: 100%">
            <el-table-column prop="nodeOrder" label="序号" width="80"></el-table-column>
            <el-table-column prop="title" label="任务名称" width="150"></el-table-column>
            <el-table-column prop="description" label="任务描述"></el-table-column>
            <el-table-column label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="执行证明" width="120">
              <template slot-scope="scope">
                <!-- 处理二进制图片 -->
                <div v-if="scope.row.id">
                  <el-image 
                    v-if="!scope.row.imageLoadFailed"
                    style="width: 50px; height: 50px; border-radius: 4px;" 
                    :src="getTaskImageUrl(scope.row.id)"
                    fit="cover"
                    @load="onImageLoad(scope.row.id)"
                    @error="onImageError(scope.row.id)">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                  <div v-else class="no-image-placeholder">
                    <i class="el-icon-picture-outline"></i>
                    <span>无图片</span>
                  </div>
                </div>
                <span v-else>暂无</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <!-- 接单者上传执行证明 -->
                <div v-if="orderType === 'accepted' && scope.row.status === 0">
                  <el-button type="primary" size="mini" @click="handleUpload(scope.row)">上传执行证明</el-button>
                </div>
                
                <!-- 发布者确认任务 -->
                <div v-if="orderType === 'published' && scope.row.status === 1">
                  <el-button type="success" size="mini" @click="confirmTask(scope.row)">确认完成</el-button>
                </div>

                <!-- 已确认的任务 -->
                <span v-if="scope.row.status === 2">已确认完成</span>
              </template>
            </el-table-column>
          </el-table>

          <!-- 订单结算部分 -->
          <div class="settlement" style="margin-top: 30px; text-align: right;" 
            v-if="allTasksCompleted && orderType === 'published' && !paymentCompleted">
            <el-alert
              title="所有任务已完成，可以进行结算"
              type="success"
              :closable="false"
              style="margin-bottom: 20px;">
            </el-alert>
            <el-button type="primary" @click="handlePayment">订单结算</el-button>
          </div>
        </div>

        <!-- 无订单时的提示 -->
        <el-empty v-if="!selectedOrderId" :description="getEmptyDescription()"></el-empty>
      </div>
    </el-card>

    <!-- 上传执行证明对话框 -->
    <el-dialog title="上传执行证明" :visible.sync="uploadDialogVisible" width="500px">
      <el-form :model="uploadForm" :rules="uploadRules" ref="uploadForm" label-width="100px">
        <el-form-item label="执行照片" prop="proofImage">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            accept="image/*">
            <el-button size="small" type="primary">选择图片</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="执行说明" prop="proofDescription">
          <el-input
            type="textarea"
            v-model="uploadForm.proofDescription"
            :rows="3"
            placeholder="请输入执行说明">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelUpload">取 消</el-button>
        <el-button type="primary" :loading="uploadLoading" @click="submitUpload">确 认</el-button>
      </div>
    </el-dialog>

    <!-- 支付对话框 -->
    <el-dialog title="订单结算" :visible.sync="paymentDialogVisible" width="500px">
      <el-result icon="success" title="订单结算" subTitle="所有任务已完成，请进行支付">
        <template slot="extra">
          <el-descriptions title="订单信息" :column="1" border>
            <el-descriptions-item label="订单编号">{{ orderId }}</el-descriptions-item>
            <el-descriptions-item label="服务项目">宠物照料服务</el-descriptions-item>
            <el-descriptions-item label="订单金额">￥{{ orderAmount.toFixed(2) }}</el-descriptions-item>
          </el-descriptions>
          <div style="margin-top: 20px;">
            <el-button type="primary" @click="confirmPayment">确认支付</el-button>
            <el-button @click="paymentDialogVisible = false">取消</el-button>
          </div>
        </template>
      </el-result>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'TaskNode',
  data() {
    return {
      // 基本信息
      orderType: 'published', // 'published'(我发布的) 或 'accepted'(我接受的)
      selectedOrderId: null,
      orderList: [],
      orderId: null,
      petName: '',
      petType: '',
      orderStatus: '',
      
      // 任务节点相关
      taskNodeForm: {
        taskNodes: []
      },
      taskNodes: [],
      taskNodesCreated: false,
      
      // 上传对话框
      uploadDialogVisible: false,
      currentTask: null,
      uploadForm: {
        proofImage: null,
        proofDescription: ''
      },
      uploadRules: {
        proofImage: [
          { required: true, message: '请上传执行照片', trigger: 'change' }
        ],
        proofDescription: [
          { required: true, message: '请输入执行说明', trigger: 'blur' }
        ]
      },
      fileList: [],
      uploadLoading: false,
      
      // 支付对话框
      paymentDialogVisible: false,
      orderAmount: 199.00,
      paymentCompleted: false,
      loading: false
    }
  },
  computed: {
    orderStatusType() {
      const statusMap = {
        'pending': 'info',
        'processing': 'warning',
        'completed': 'success',
        'cancelled': 'danger'
      }
      return statusMap[this.orderStatus] || 'info'
    },
    orderStatusText() {
      const statusMap = {
        'pending': '待处理',
        'processing': '进行中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[this.orderStatus] || '未知状态'
    },
    allTasksCompleted() {
      return this.taskNodes.every(node => node.status === 2)
    },
    currentUser() {
      return this.$store.state.user;
    }
  },
  watch: {
    currentUser: {
      handler(newVal) {
        console.log('用户信息变化:', newVal);
        if (newVal && newVal.id) {
          this.fetchOrders();
        }
      },
      immediate: true
    }
  },
  created() {
    console.log('组件创建，当前用户信息:', this.currentUser);
    // 检查用户是否已登录
    if (!this.currentUser || !this.currentUser.id) {
      this.$message.warning('请先登录');
      // 可以选择重定向到登录页面
      // this.$router.push('/login');
      return;
    }
    
    // 初始化时获取订单列表
    this.fetchOrders();
    
    // 如果URL中包含orderId，则自动选择该订单
    if (this.$route.query.orderId) {
      this.selectedOrderId = this.$route.query.orderId;
      this.fetchOrderDetails();
      this.fetchTaskNodes();
    }
  },
  methods: {
    // 处理订单类型切换
    handleOrderTypeChange(type) {
      this.selectedOrderId = null;
      this.taskNodes = [];
      this.taskNodesCreated = false;
      this.fetchOrders();
    },

    // 获取订单列表
    fetchOrders() {
      // 从Vuex中获取用户信息
      const userInfo = this.$store.state.user;
      console.log('当前用户信息:', userInfo);
      
      const userId = userInfo ? userInfo.userId || userInfo.id : null;
      console.log('当前用户ID:', userId);
      
      if (!userId) {
        this.$message.error('请先登录');
        return;
      }
      
      const url = this.orderType === 'published' 
        ? `/api/pet-care/orders/published/${userId}` 
        : `/api/pet-care/orders/accepted/${userId}`;
      
      console.log('请求URL:', url);
      console.log('请求类型:', this.orderType);
      
      this.loading = true;
      request({
        url: url,
        method: 'get'
      }).then(response => {
        this.loading = false;
        console.log('API响应:', response);
        if (response.code === 200) {
          this.orderList = response.data || [];
          console.log('订单列表:', this.orderList);
          if (this.orderList.length === 0) {
            this.$message.info(this.orderType === 'published' ? '您还没有发布过订单' : '您还没有接受过订单');
          }
        } else {
          this.$message.error(response.msg || '获取订单列表失败');
        }
      }).catch(error => {
        this.loading = false;
        console.error('获取订单列表失败:', error);
        this.$message.error('获取订单列表失败，请检查网络连接');
      });
    },

    // 处理订单选择
    handleOrderSelect(orderId) {
      this.orderId = orderId;
      this.fetchOrderDetails();
      this.fetchTaskNodes();
    },

    // 获取订单标签显示
    getOrderLabel(order) {
      const serviceTypeText = order.serviceType || '未知服务';
      const priceText = order.price ? `￥${order.price}` : '';
      return `${order.petName} - ${serviceTypeText} ${priceText}`;
    },

    // 获取空状态描述
    getEmptyDescription() {
      return this.orderType === 'published' 
        ? '您还没有发布过订单' 
        : '您还没有接受过订单';
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
    },

    // 获取订单详情
    fetchOrderDetails() {
      if (!this.selectedOrderId) return;
      
      request({
        url: `/api/pet-care/orders/${this.selectedOrderId}`,
        method: 'get'
      }).then(response => {
        if (response.code === 200) {
          const order = response.data;
          this.petName = order.petName;
          this.petType = order.petType;
          this.orderStatus = order.status;
        }
      }).catch(error => {
        console.error('获取订单详情失败:', error);
        this.$message.error('获取订单详情失败');
      });
    },

    // 获取任务节点
    fetchTaskNodes() {
      if (!this.selectedOrderId) return;
      
      request({
        url: `/api/pet-care/orders/${this.selectedOrderId}/task-nodes`,
        method: 'get'
      }).then(response => {
        if (response.code === 200) {
          this.taskNodes = response.data;
          this.taskNodesCreated = this.taskNodes.length > 0;
          
          // 调试输出，查看返回的数据结构
          console.log('获取到的任务节点:', this.taskNodes);
          
          // 检查图片数据
          if (this.taskNodes && this.taskNodes.length > 0) {
            this.taskNodes.forEach((node, index) => {
              console.log(`节点${index+1}的标题: ${node.title}`);
              if (node.proofImage) {
                console.log(`节点${index+1}的proofImage类型:`, typeof node.proofImage);
                console.log(`节点${index+1}的proofImage长度:`, 
                  Array.isArray(node.proofImage) ? node.proofImage.length : '未知');
              }
              if (node.mediaUrls) {
                console.log(`节点${index+1}的mediaUrls:`, node.mediaUrls.substring(0, 50) + '...');
              }
            });
          }
        }
      }).catch(error => {
        console.error('获取任务节点失败:', error);
        this.$message.error('获取任务节点失败');
      });
    },

    // 添加任务节点
    addTaskNode() {
      const newNode = {
        title: '',
        description: '',
        nodeOrder: this.taskNodes.length + 1,
        status: 0
      };
      this.taskNodes.push(newNode);
    },
    
    // 移除任务节点
    removeTaskNode(index) {
      this.taskNodes.splice(index, 1);
      // 更新剩余节点的顺序
      this.taskNodes.forEach((node, idx) => {
        node.nodeOrder = idx + 1;
      });
    },
    
    // 提交任务节点
    submitTaskNodes() {
      if (!this.selectedOrderId) {
        this.$message.error('请先选择订单');
        return;
      }
      if (!this.taskNodes || this.taskNodes.length === 0) {
        this.$message.error('请添加至少一个任务节点');
        return;
      }

      // 提交任务节点
      request({
        url: `/api/pet-care/orders/${this.selectedOrderId}/task-nodes/init`,
        method: 'post',
        data: this.taskNodes
      }).then(response => {
        if (response.code === 200) {
          this.$message.success('提交成功');
          this.fetchTaskNodes();
        } else {
          this.$message.error(response.msg || '提交失败');
        }
      }).catch(error => {
        console.error('提交任务节点失败:', error);
        this.$message.error('提交失败，请检查网络连接');
      });
    },
    
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: 'info',    // 待完成
        1: 'warning', // 已完成待确认
        2: 'success'  // 已确认
      }
      return statusMap[status] || 'info'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待完成',
        1: '待确认',
        2: '已完成'
      }
      return statusMap[status] || '未知状态'
    },
    
    // 处理上传操作
    handleUpload(task) {
      this.currentTask = task
      this.uploadDialogVisible = true
      this.uploadForm.proofDescription = ''
      this.fileList = []
    },
    
    // 确认任务完成
    confirmTask(task) {
      this.$confirm('确认该任务已完成吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        // 实际应用中应调用API确认任务
        console.log('确认任务完成:', task)
        
        // 模拟API请求
        setTimeout(() => {
          // 更新状态
          const index = this.taskNodes.findIndex(node => node.nodeOrder === task.nodeOrder)
          if (index !== -1) {
            this.taskNodes[index].status = 2
            this.$message.success('任务确认完成')
            
            // 检查是否所有任务都已完成
            if (this.allTasksCompleted) {
              this.$message({
                message: '所有任务已完成，可以进行订单结算',
                type: 'success',
                duration: 3000
              })
            }
          }
        }, 500)
      }).catch(() => {
        this.$message.info('已取消确认')
      })
    },
    
    // 处理文件变更
    handleFileChange(file) {
      const isImage = file.raw.type.startsWith('image/');
      const isLt2M = file.raw.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }

      // 转换图片为base64
      const reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = () => {
        const base64Result = reader.result.split(',');
        this.uploadForm.proofImage = base64Result[1]; // 去掉base64头部信息
        console.log('图片已转换为base64');
      };
      this.fileList = [file];
    },
    
    // 处理文件移除
    handleFileRemove() {
      this.uploadForm.proofImage = null;
      this.fileList = [];
    },
    
    // 取消上传
    cancelUpload() {
      this.uploadDialogVisible = false;
      this.uploadForm.proofImage = null;
      this.uploadForm.proofDescription = '';
      this.fileList = [];
      this.currentTask = null;
    },
    
    // 提交上传
    submitUpload() {
      this.$refs.uploadForm.validate(valid => {
        if (valid) {
          if (!this.currentTask || !this.currentTask.id) {
            this.$message.error('任务信息无效');
            return;
          }

          // 使用FormData处理二进制文件上传
          const formData = new FormData();
          formData.append('id', this.currentTask.id);
          formData.append('title', this.currentTask.title);
          formData.append('nodeOrder', this.currentTask.nodeOrder);
          formData.append('orderId', this.selectedOrderId);
          formData.append('proofDescription', this.uploadForm.proofDescription);
          formData.append('proofText', this.uploadForm.proofDescription);
          formData.append('status', 1);
          
          // 添加文件到FormData，直接上传文件而不是Base64
          if (this.fileList && this.fileList.length > 0) {
            const fileObj = this.fileList[0];
            if (fileObj.raw) {
              formData.append('file', fileObj.raw);
              console.log('添加文件到FormData，文件名:', fileObj.name, '文件类型:', fileObj.raw.type, '文件大小:', fileObj.raw.size);
            } else {
              this.$message.error('文件对象无效，请重新选择文件');
              return;
            }
          } else {
            this.$message.error('请选择要上传的图片');
            return;
          }
          
          console.log('提交数据表单...');
          this.uploadLoading = true;

          // 使用请求适用于FormData
          request({
            url: `/api/pet-care/orders/${this.selectedOrderId}/task-nodes/${this.currentTask.id}/upload`,
            method: 'post',
            data: formData,
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(response => {
            this.uploadLoading = false;
            if (response.code === 200) {
              this.$message.success('提交成功');
              this.uploadDialogVisible = false;
              // 延迟一下再刷新，确保服务器处理完成
              setTimeout(() => {
                this.fetchTaskNodes(); // 刷新任务列表
              }, 500);
            } else {
              this.$message.error(response.msg || '提交失败');
            }
          }).catch(error => {
            this.uploadLoading = false;
            console.error('提交执行证明失败:', error);
            this.$message.error('提交失败，请检查网络连接' + (error.message ? ': ' + error.message : ''));
          });
        }
      });
    },
    
    // 处理支付操作
    handlePayment() {
      this.paymentDialogVisible = true
    },
    
    // 确认支付
    confirmPayment() {
      // 实际应用中应调用支付API
      console.log('确认支付:', this.orderId, this.orderAmount)
      
      // 模拟支付过程
      this.$message({
        message: '正在处理支付...',
        type: 'info'
      })
      
      // 模拟API请求
      setTimeout(() => {
        this.paymentDialogVisible = false
        this.paymentCompleted = true
        this.orderStatus = 'completed'
        
        this.$notify({
          title: '支付成功',
          message: `订单 ${this.orderId} 已完成支付，金额：￥${this.orderAmount.toFixed(2)}`,
          type: 'success',
          duration: 5000
        })
      }, 1500)
    },

    // 获取任务图片URL
    getTaskImageUrl(taskId) {
      if (!taskId) return '';
      // 使用正确的API路径获取图片
      return process.env.VUE_APP_BASE_API + `/api/pet-care/task-nodes/${taskId}/image?t=${new Date().getTime()}`;
    },

    // 处理图片加载
    onImageLoad(taskId) {
      console.log(`图片加载成功: 任务节点 ${taskId}`);
      // 清除之前可能存在的错误标记
      const nodeIndex = this.taskNodes.findIndex(node => node.id === taskId);
      if (nodeIndex !== -1) {
        this.$set(this.taskNodes[nodeIndex], 'imageLoadFailed', false);
      }
    },
    
    // 处理图片加载错误
    onImageError(taskId) {
      console.error(`图片加载失败: 任务节点 ${taskId}，请检查二进制数据是否存在`);
      
      // 检查并更新状态以避免反复请求失败的图片
      const nodeIndex = this.taskNodes.findIndex(node => node.id === taskId);
      if (nodeIndex !== -1) {
        // 标记为图片加载失败，可以在UI中显示替代内容
        this.$set(this.taskNodes[nodeIndex], 'imageLoadFailed', true);
      }
    },
  }
}
</script>

<style scoped>
.task-node-item {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}
.role-switch {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  margin: 15px 0;
}
.settlement {
  background-color: #f0f9eb;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.order-selection {
  margin: 20px 0;
}
.no-image-placeholder {
  width: 50px;
  height: 50px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
  font-size: 12px;
}
.no-image-placeholder i {
  font-size: 20px;
  margin-bottom: 2px;
}
</style>